<template>
  <a-layout>
    <a-layout-sider style="background-color: white" :width="400">
      <a-table
        :columns="columns"
        :data-source="treeData"
        size="small"
        :pagination="false"
      >
        <template #bodyCell="{ column, record }">
          <template v-if="column.dataIndex === 'operate'">
            <!-- <a-tag v-if="record['code'].length > 0">{{ record["code"] }}</a-tag> -->
            <a-button
              v-if="record['code'].length > 0"
              type="link"
              @click="restore(record)"
            >
              恢复
            </a-button>
            <a-button
              v-if="record['code'].length > 0"
              type="link"
              danger
              @click="dropField(record)"
            >
              删除
            </a-button>
            <a-button
              v-if="CommonDefine.usefulArray(record['children'])"
              type="link"
              @click="loadRecords(record)"
              >记录</a-button
            >
          </template>
        </template>
      </a-table>
    </a-layout-sider>
    <a-layout-content style="background-color: white; padding-left: 4px">
      <a-flex gap="small" justify="flex-end">
        <a-button
          type="primary"
          :disabled="state.selectedRowKeys.length < 1"
          @click="restoreRecords"
          >回收</a-button
        >
        <a-button
          danger
          :disabled="state.selectedRowKeys.length < 1"
          @click="dropRecords"
          >彻底删除</a-button
        >
      </a-flex>
      <a-table
        :columns="state.cols"
        :data-source="lstDisplay"
        bordered
        size="small"
        :pagination="false"
        :row-selection="rowSelection"
      >
        <template #bodyCell="{ column, record }">
          <template v-if="column.dataIndex == '#'">
            <span>{{ record[column.dataIndex] }}</span>
          </template>
          <template v-if="column.multi">
            <a-button
              v-if="record[column.dataIndex]"
              @click="goViewMultiFieldValues(record, column)"
              ><EllipsisOutlined
            /></a-button>
          </template>
          <template v-if="column.type == 'FtBool'">
            <a-checkbox
              v-model:checked="record[column.dataIndex]"
              disabled
            ></a-checkbox>
          </template>
          <template
            v-if="column.type == 'FtModel' || column.type == 'FtModelSelf'"
          >
            <span>{{ record[column.dataIndex] }}</span>
          </template>
          <template v-if="column.type == 'FtFile'">
            <a href="#DownloadFile" @click="downloadFile(record, column)">{{
              record[column.dataIndex]
            }}</a>
          </template>
        </template>
      </a-table>
    </a-layout-content>
    <a-modal
      v-model:open="state.popRestoreConfig"
      :footer="null"
      title="恢复选项"
    >
      <a-form layout="vertical" :model="formRestore">
        <a-form-item label="恢复记录">
          <a-switch v-model:checked="formRestore.withValues"></a-switch>
        </a-form-item>
        <a-form-item label="要恢复的字段" v-if="state.restoreModel">
          <FieldInTrashSelector
            ref="refFieldSelector"
            :fields="state.fieldsOfCurrentModel"
            :multi="true"
            @ok="onFieldSelected"
          ></FieldInTrashSelector>
        </a-form-item>
        <a-form-item>
          <a-button @click="doRestore">继续操作</a-button>
        </a-form-item>
      </a-form>
    </a-modal>
  </a-layout>
</template>
<script setup>
import { onMounted, reactive, computed } from "vue";
import CommonDefine from "@/component/CommonDefine";
import { useI18n } from "vue-i18n";
import FieldInTrashSelector from "@/component/field/FieldInTrashSelector.vue";

const { t } = useI18n();

const columns = [
  { title: t("129"), dataIndex: "label" },
  { title: "操作", dataIndex: "operate" },
];

const state = reactive({
  popRestoreConfig: false,
  pageIndex: 0,
  hasMoreRecords: false,
  lastIndex: 0,
  cols: [],
  selectedRowKeys: [],
  currnetModel: undefined, //当前选中节点的归属模型节点
  fieldsOfCurrentModel: [], // 当前选中节点的归属模型的所有在回收站内的字段列表
  restoreModel: false, // 当前选中节点是恢复模型还是恢复字段
});

const rowSelection = computed(() => {
  return {
    selectedRowKeys: state.selectedRowKeys,
    onChange: (eve) => {
      state.selectedRowKeys = eve;
    },
  };
});

const treeData = reactive([]);

const loadTreeOfTrash = () => {
  treeData.splice(0, treeData.length);
  CommonDefine.apiGetArm(`/api/v1/record/trash`, (d) => {
    d.forEach((node) => {
      treeData.push(node);
    });
  });
};

const _cols = (fieldNodes) => {
  CommonDefine.clearArray(state.cols);
  state.cols.push({ dataIndex: "#", title: "#", width: 80, align: "right" });
  fieldNodes.forEach((field) => {
    let col = {
      dataIndex: field.key,
      title: field.label,
      ellipsis: true,
    };
    state.cols.push(col);
  });
};

const lstDisplay = reactive([]);
const lstRecord = reactive([]);

// 填充rec.display属性
const _recArrayToDisplayArray = () => {
  CommonDefine.clearArray(lstDisplay);
  lstRecord.forEach((record, index) => {
    let display = {};
    display["#"] = index + 1;
    display["key"] = record.recordId;
    Object.keys(record.value).forEach((key) => {
      display[key] = record.value[key].C + "";
    });
    lstDisplay.push(display);
  });
};

const _loadRecordsInTrash = (fieldIds) => {
  let pd = {
    fieldIds,
    pageIndex: 1,
    pageSize: 100,
  };
  CommonDefine.clearArray(lstRecord);
  CommonDefine.apiPostArm("/api/v1/record/in-trash", pd, (d) => {
    d.forEach((record) => {
      lstRecord.push(record);
    });
    _recArrayToDisplayArray();
  });
};

const loadRecords = (record) => {
  state.currnetModel = record;
  _cols(state.currnetModel.children);
  _loadRecordsInTrash(state.currnetModel.children.map((x) => x.key));
};

const dropRecords = () => {
  let pd = {
    recordIds: state.selectedRowKeys,
  };
  CommonDefine.apiPostArm("/api/v1/record/drop-from-trash", pd, (d) => {
    // console.log(state.selectedRowKeys);
    state.selectedRowKeys.forEach((recordId) => {
      let idx = lstRecord.findIndex((rdd) => rdd.recordId == recordId);
      lstRecord.splice(idx, 1);
    });
    state.selectedRowKeys = [];
    _recArrayToDisplayArray();
  });
};

const dropField = (record) => {
  // 默认删除字段，ext为空说明是模型节点，走删除模型服务
  let pd = { fid: record.key };
  let url = "/api/v1/model/drop-field";
  if (record.ext == null || record.ext.length < 1) {
    url = "/api/v1/model/drop";
    pd = { modelId: record.key };
  }
  CommonDefine.apiPostArm(url, pd, (d) => {
    loadTreeOfTrash();
  });
};

const formRestore = reactive({});
const onFieldSelected = (eve) => {
  formRestore.fieldIds = eve;
};

const restore = (record) => {
  if (record.ext == null || record.ext.length < 1) {
    // model
    state.restoreModel = true;
    formRestore.modelId = record.key;
    delete formRestore.fieldIds;
    // 将该模型下的回收站里的字段列出
    CommonDefine.clearArray(state.fieldsOfCurrentModel);
    record.children.forEach((fieldNode) => {
      if (fieldNode.code != null && fieldNode.code.length > 0) {
        state.fieldsOfCurrentModel.push(JSON.parse(fieldNode.ext));
      }
    });
  } else {
    // field
    state.restoreModel = false;
    let fieldObj = JSON.parse(record.ext);
    state.fieldsOfCurrentModel = [fieldObj];
    formRestore.modelId = fieldObj.modelId;
    formRestore.fieldIds = [record.key];
  }
  state.popRestoreConfig = true;
};

const doRestore = () => {
  CommonDefine.apiPostArm("/api/v1/model/restore", formRestore, (d) => {
    state.popRestoreConfig = false;
    loadTreeOfTrash();
  });
};

const restoreRecords = () => {
  let pd = {
    recordIds: state.selectedRowKeys,
    modelId: state.currnetModel.key,
    fieldIds: state.currnetModel.children
      // .filter((x) => {
      //   return x.code != null && x.code.length > 0;
      // })
      .map((x) => x.key),
  };
  CommonDefine.apiPostArm("/api/v1/record/restore", pd, (d) => {
    _loadRecordsInTrash(state.currnetModel.children.map((x) => x.key));
  });
};

onMounted(() => {
  loadTreeOfTrash();
});
</script>
